import {forwardRef, useEffect, useImperativeHandle} from "react";
import AMapLoader from "@amap/amap-jsapi-loader";

declare global {
  interface Window {
    _AMapSecurityConfig: any;
  }
}

let map: any;
let autoComplete: any
let marker: any
let AMapC: any
let driving: any

const MapContainer = forwardRef((props: any, ref) => {

  console.log('props = ', props)

  useEffect(() => {
    window._AMapSecurityConfig = {
      securityJsCode: "19af0a7c3c760971fbb3508b18abad98",
    };

    AMapLoader.load({
      key: "ec163362391a3d3af59d4a54fef6648e", // 申请好的Web端开发者Key，首次调用 load 时必填
      version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: ['AMap.AutoComplete', 'AMap.Driving'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    })
      .then((AMap) => {
        AMapC = AMap

        map = new AMap.Map("container", {
          // 设置地图容器id
          // viewMode: "3D", // 是否为3D地图模式
          zoom: 11, // 初始化地图级别
          // center: [116.397428, 39.90923], // 初始化地图中心点位置
        });

        let autoOptions = {
          // city 限定城市，默认全国
          // city: "全国",
        };
        // 实例化AutoComplete
        autoComplete = new AMap.AutoComplete(autoOptions);

        driving = new AMap.Driving({
          map: map,
          // panel: "my-panel",
        });

        if (props.init) {
          props.init()
        }

      })
      .catch((e) => {
        console.log(e);
      });

    return () => {
      console.log(`map?.destroy()`)
      map?.destroy();
    };
  }, []);

  useImperativeHandle(ref, () => ({
    // changeVal 就是暴露给父组件的方法
    map: () => map,
    autoComplete: () => autoComplete,
    AMapC: () => AMapC,
    driving: () => driving,
    clearMarker: () => {
      if (marker) {
        map.remove(marker)
      }
    },
    addMarker: (location: any) => {
      console.log('addMarker location = ', location)
      if (marker) {
        map.remove(marker)
      }

      marker = new AMapC.Marker({
        // icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
        position: location,
        // offset: new AMapC.Pixel(-13, -30)
      });

      marker.setMap(map);

      map.setZoomAndCenter(15, location)
    }
  }));
  return <div id="container" style={{height: '30vh', ...props.style}}></div>
});

export default MapContainer
